package com.smedi.ismedi.constructionproject.core.application.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.cache.starter.util.RedisUtil;
import com.smedi.ismedi.constructionproject.core.application.command.*;
import com.smedi.ismedi.constructionproject.core.application.convert.AppConverter;
import com.smedi.ismedi.constructionproject.core.application.query.ProjectApplyQueryService;
import com.smedi.ismedi.constructionproject.core.application.service.ProjectApplyApplicationService;
import com.smedi.ismedi.constructionproject.core.domain.aggregatemodel.*;
import com.smedi.ismedi.constructionproject.core.domain.dto.PersonQuery;
import com.smedi.ismedi.constructionproject.core.domain.repository.PersonBasicRepository;
import com.smedi.ismedi.constructionproject.core.domain.repository.ProjectApplyRepository;
import com.smedi.ismedi.constructionproject.core.domain.repository.ProjectAssignmentRepository;
import com.smedi.ismedi.constructionproject.core.domain.repository.ProjectBasicRepository;
import com.smedi.ismedi.constructionproject.core.domain.service.ProjectApplyDomainService;
import com.smedi.ismedi.constructionproject.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.constructionproject.core.infrastructure.enumerate.ApplyStatusEnum;
import com.smedi.ismedi.constructionproject.core.infrastructure.enumerate.MonitorTypeEnum;
import com.smedi.ismedi.constructionproject.core.port.adapter.service.*;
import com.smedi.ismedi.organization.api.dto.response.HrOrganizationResponse;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.smedi.ismedi.constructionproject.core.infrastructure.constant.ConstantField.*;

/**
 * @Author: xulinjun
 * @Date: 2021-6-24 15:33
 */
@Slf4j
@Service
@AllArgsConstructor

public class ProjectApplyApplicationServiceImpl implements ProjectApplyApplicationService {
    private final AppConverter appConverter;

    private final ProjectApplyDomainService projectApplyDomainService;

    private final ProcessRemoteService processRemoteService;

    private final ProjectApplyQueryService projectApplyQueryService;

    private final ProjectBasicRepository projectBasicRepository;

    private final ProjectAssignmentRepository projectAssignmentRepository;

    private final ProjectApplyRepository projectApplyRepository;

    private final TaskRemoteService taskRemoteService;

    private final AuthorityUtil authorityUtil;

    private final RedisUtil redisUtil;

    private final AuthorityAccessRemoteApiService AuthorityAccessRemoteApiService;

    private final PersonBasicRepository personBasicRepository;

    private final MessageRemoteApiService messageRemoteApiService;

    private final OrganizationRemoteApiService organizationRemoteApiService;

    private final PersonnelRemoteApiService personnelRemoteApiService;

    @Override
    public String getBusinessToken() {
        String token = UUID.fastUUID().toString();
        redisUtil.set(PROJECT_APPLY_KEY + COLONS + token, 1, TOKEN_EFFECTIVE_TIME);
        return token;
    }

    @Override
    public ProjectApply postSave(ProjectApplyCreateCommand projectApplyCreateCommand) {
        projectApplyCreateCommand.setApplyCode(java.util.UUID.randomUUID().toString());

        List<Long> personIds = new ArrayList<>();

        this.validKey(projectApplyCreateCommand.getBusinessToken());

        ProjectBasic projectBasic = projectBasicRepository.selectByProjectId(projectApplyCreateCommand.getProjectId());
        // 获取可以进行主体院审批的人
        List<Person> dealPeople = personnelRemoteApiService.getPersonList(PersonQuery.builder().roleName("主体院EPC分管领导").organizationId(projectBasic.getHrOrganizationId()).build());
        if (CollectionUtils.isEmpty(dealPeople)) {
            throw LogicException.raise(CustomError.EPC_LEADER_ID_MISS);
        }
        //1. 如果该项目已是免装项目，再次申请免装或暂停时，提示“该项目已被设为免装项目，无需再次进行申请！”
        if (projectBasic.getMonitorType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue())) {
            throw LogicException.raise(CustomError.PROJECT_FREE_INSTALL);
        }
        //2. 如果该项目已是暂停项目，仍然申请暂停，则提示“该项目已被设为暂停项目，无需再次进行申请！” （如果是暂停项目已经恢复了，则视为正常项目，这时可以再次申请）
        if (projectBasic.getMonitorType().equals(MonitorTypeEnum.STOPPED.getValue()) && projectApplyCreateCommand.getApplyType().equals(MonitorTypeEnum.STOPPED.getValue())) {
            throw LogicException.raise(CustomError.PROJECT_STOP);
        }
        //如果此项目有正在进行的申请，不允许申请
        List<ProjectApply> projectApplyList = projectApplyRepository.getProjectApplyList(ProjectApplyQuery.builder().projectId(projectApplyCreateCommand.getProjectId()).build());
        if (CollectionUtils.isNotEmpty(projectApplyList)) {
            List<ProjectApply> projectApplies = projectApplyList.stream().filter(x -> !x.getTaskStatus().equals(BACK_STATE) && !x.getTaskStatus().equals(FINISHED)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(projectApplies)) {
                throw LogicException.raise(CustomError.PROJECT_APPLYING);
            }
        }
        ProjectApply projectApply = appConverter.projectApplyCreateCommandToProjectAppy(projectApplyCreateCommand);
        if (projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue())) {
            processRemoteService.startProcessInstance(ProcessInstanceStartCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY)
                    .build());

            ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY)
                    .build());

            projectApply.setTaskStatus(processTask.getStatus());
            projectApply.setTaskKey(processTask.getTaskDefinitionKey());
            projectApply.setApplyStatus(ApplyStatusEnum.APPROVAL.getValue());
        }
        if (projectApply.getApplyType().equals(MonitorTypeEnum.STOPPED.getValue())) {
            processRemoteService.startProcessInstance(ProcessInstanceStartCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY_STOP)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY_STOP)
                    .build());

            ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY_STOP)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY_STOP)
                    .build());

            projectApply.setTaskStatus(processTask.getStatus());
            projectApply.setTaskKey(processTask.getTaskDefinitionKey());
            projectApply.setApplyStatus(ApplyStatusEnum.APPROVAL.getValue());
        }
        ProjectApply saveProjectApply = projectApplyDomainService.saveProjectApply(projectApply);

        if (CollectionUtils.isNotEmpty(dealPeople)) {
            // 发送待办
            this.sendTask(saveProjectApply, dealPeople);
            //发送短信
            sendMessageProjectApply(dealPeople, saveProjectApply);
        }
        return saveProjectApply;
    }

    @Override
    @Transactional
    public ProjectApply postEdit(ProjectApplyEditCommand projectApplyEditCommand) {
        List<Long> personIds = new ArrayList<>();
        ProjectApply saveProjectApplyReturn = new ProjectApply();
        //如果此项目有正在进行的申请，不允许申请
        List<ProjectApply> projectApplyList = projectApplyRepository.getProjectApplyList(ProjectApplyQuery.builder().projectId(projectApplyEditCommand.getProjectId()).build());
        if (CollectionUtils.isNotEmpty(projectApplyList)) {
            List<ProjectApply> projectApplies = projectApplyList.stream().filter(x -> !x.getTaskStatus().equals(BACK_STATE) && !x.getTaskStatus().equals(FINISHED)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(projectApplies)) {
                throw LogicException.raise(CustomError.PROJECT_APPLYING);
            }
        }
        ProjectApply projectApply = projectApplyQueryService.getProjectApplyOne(ProjectApplyOneQuery.builder().id(projectApplyEditCommand.getId()).build());

        //获取主体院EPC分管领导
        List<Person> dealPeople = personnelRemoteApiService.getPersonList(PersonQuery.builder().roleName("主体院EPC分管领导").organizationId(projectApply.getProject().getHrOrganizationId()).build());
        if (CollectionUtils.isEmpty(dealPeople)) {
            throw LogicException.raise(CustomError.EPC_LEADER_ID_MISS);
        }
        if (!projectApplyEditCommand.getApplyType().equals(projectApply.getApplyType())) {
            ProjectApplyCreateCommand projectApplyCreateCommand = appConverter.projectApplyEditCommandToCreateCommand(projectApplyEditCommand);

            saveProjectApplyReturn = postSave(projectApplyCreateCommand);
            ProjectApply projectApplyDelete = appConverter.projectApplyEditCommandProjectApply(projectApplyEditCommand);

            projectApplyRepository.deleteProjectApply(projectApplyDelete);
        } else {
            // ProjectApply projectApply2 = appConverter.projectApplyEditCommandProjectApply(projectApplyEditCommand);
            ProjectApply projectApply1 = appConverter.projectApplyEditCommandProjectApply(projectApplyEditCommand);
            projectApply.setApplyReason(projectApply1.getApplyReason());
            projectApply.setApplyType(projectApply1.getApplyType());
            projectApply.setFiles(projectApply1.getFiles());
            projectApply.setProject(projectApply1.getProject());

            if (projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue())) {
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(projectApply.getApplyCode())
                        .businessType(PROJECT_APPLY)
                        .processDefinitionKey(PROCESS_PROJECT_APPLY)
                        .build());

                projectApply.setTaskStatus(processTask.getStatus());
                projectApply.setTaskKey(processTask.getTaskDefinitionKey());
            }
            if (projectApply.getApplyType().equals(MonitorTypeEnum.STOPPED.getValue())) {
                ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                        .businessCode(projectApply.getApplyCode())
                        .businessType(PROJECT_APPLY_STOP)
                        .processDefinitionKey(PROCESS_PROJECT_APPLY_STOP)
                        .build());

                projectApply.setTaskStatus(processTask.getStatus());
                projectApply.setTaskKey(processTask.getTaskDefinitionKey());
            }
            projectApply.setApplyStatus(ApplyStatusEnum.APPROVAL.getValue());
//        if (processTask.getStatus().equals(BACK_STATE)) {
//            projectApply.setApplyStatus(ApplyStatusEnum.APPROVAL.getValue());
//        }
            ProjectApply saveProjectApply = projectApplyDomainService.editProjectApply(projectApply);


            // 发送待办
            this.sendTask(saveProjectApply, dealPeople);
            // 更新 退回申请 待办
            List<String> oldStatus = new ArrayList<>();
            oldStatus.add(DEALING);
            taskRemoteService.editTask(TaskRecordEditCommand.builder()
                    .sourceFromId(projectApply.getId())
                    .taskType(MONITOR_VIEW)
                    .taskName(FREE_INSTALL_APPLY_RETURN)
                    .projectId(projectApply.getProject().getProjectId())
                    .projectName(projectApply.getProject().getProjectName())
                    .taskDescribe(projectApply.getProject().getProjectShortName())
                    .startTime(projectApply.getApplyTime())
                    .oldStatus(oldStatus)
                    .taskStatus("已完成")
                    .build());

            //发送短信
            sendMessageProjectApply(dealPeople, saveProjectApply);

            saveProjectApplyReturn = saveProjectApply;
        }
        return saveProjectApplyReturn;
    }

    @Override
    @Transactional
    public ProjectApply instituteLeaderApproval(ProcessInstituteLeaderApprovalCommand approvalCommand) {
        // 工程部工程师
        List<Person> persons = personnelRemoteApiService.getPersonList(PersonQuery.builder().roleName("工程部工程师-视频监控审批").build());
        if (CollectionUtils.isEmpty(persons)) {
            throw LogicException.raise(CustomError.ENGINEER_LEADER_ID_MISS);
        }
        ProjectApply projectApply = projectApplyQueryService.getProjectApplyOne(ProjectApplyOneQuery.builder().id(approvalCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, approvalCommand.getMethod());
        ProcessTask processTask = new ProcessTask();
        if (projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue())) {
            processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY)
                    .comment(approvalCommand.getComment())
                    .variables(variables)
                    .build());
        }
        if (projectApply.getApplyType().equals(MonitorTypeEnum.STOPPED.getValue())) {
            processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY_STOP)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY_STOP)
                    .comment(approvalCommand.getComment())
                    .variables(variables)
                    .build());
        }
        projectApply.setTaskStatus(processTask.getStatus());
        projectApply.setTaskKey(processTask.getTaskDefinitionKey());


        if (approvalCommand.getMethod().equals(NOT_PASS)) {
            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
        } else {
            projectApply.setApplyStatus(ApplyStatusEnum.APPROVAL.getValue());
        }
//        if (processTask.getStatus().equals(BACK_STATE)) {
//            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
//        }

        ProjectApply saveProjectApply = projectApplyDomainService.editProjectApply(projectApply);
        // 更新处理待办
        this.updateTask(saveProjectApply);


        // 发送待办
        if (!processTask.getStatus().equals(BACK_STATE)) {
            this.sendTask(saveProjectApply, persons);
            //发送短信
            sendMessageProjectApply(persons, saveProjectApply);
        } else {
            this.returnTask(saveProjectApply);
            //发退回短信
            sendMessageProjectApplyReturnOrPass(projectApply.getApplyPerson(), projectApply, "项目免装/暂停申请审批退回");
        }
        return saveProjectApply;
    }

    @Override
    @Transactional
    public ProjectApply engineerApproval(ProcessEngineerApprovalCommand approvalCommand) {
        // 工程部分管领导
        List<Person> persons = personnelRemoteApiService.getPersonList(PersonQuery.builder().roleName("工程部分管领导-视频监控审批").build());
        if (CollectionUtils.isEmpty(persons)) {
            throw LogicException.raise(CustomError.ENGINEER_MIDDLE_LEADER_ID_MISS);
        }
        ProjectApply projectApply = projectApplyQueryService.getProjectApplyOne(ProjectApplyOneQuery.builder().id(approvalCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, approvalCommand.getMethod());

        if (projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue())) {
            ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY)
                    .comment(approvalCommand.getComment())
                    .variables(variables)
                    .build());

            projectApply.setTaskStatus(processTask.getStatus());
            projectApply.setTaskKey(processTask.getTaskDefinitionKey());
        }
        if (projectApply.getApplyType().equals(MonitorTypeEnum.STOPPED.getValue())) {
            ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                    .businessCode(projectApply.getApplyCode())
                    .businessType(PROJECT_APPLY_STOP)
                    .processDefinitionKey(PROCESS_PROJECT_APPLY_STOP)
                    .comment(approvalCommand.getComment())
                    .variables(variables)
                    .build());

            projectApply.setTaskStatus(FINISHED);
            projectApply.setApplyStatus(ApplyStatusEnum.COMPLETED.getValue());
        }


        if (approvalCommand.getMethod().equals(NOT_PASS)) {
            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
        } else {
            projectApply.setApplyStatus(projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue()) ?
                    ApplyStatusEnum.APPROVAL.getValue() : ApplyStatusEnum.COMPLETED.getValue());
        }
//        if (processTask.getStatus().equals(BACK_STATE)) {
//            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
//        }
        ProjectApply saveProjectApply = projectApplyDomainService.editProjectApply(projectApply);
        // 更新处理待办
        this.updateTask(saveProjectApply);

        // 发送待办
        if (!projectApply.getTaskStatus().equals(BACK_STATE)) {
            if (projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue())) {
                this.sendTask(saveProjectApply, persons);
                //发送短信
                sendMessageProjectApply(persons, saveProjectApply);
            } else {
                projectApply.setTaskStatus(FINISHED);
                projectApply.setApplyStatus(ApplyStatusEnum.COMPLETED.getValue());
                //更新项目的监控类型
                ProjectBasic projectBasic = projectBasicRepository.selectByProjectId(projectApply.getProject().getProjectId());
                projectBasic.setMonitorType(projectApply.getApplyType());
                projectBasicRepository.doUpdate(projectBasic);
                //发通过短信
                sendMessageProjectApplyReturnOrPass(projectApply.getApplyPerson(), projectApply, "项目免装/暂停申请审批通过");
            }
        } else {
            this.returnTask(saveProjectApply);
            //发退回短信
            sendMessageProjectApplyReturnOrPass(projectApply.getApplyPerson(), projectApply, "项目免装/暂停申请审批退回");
        }

        return saveProjectApply;
    }

    @Override
    @Transactional
    public ProjectApply engineeringLeaderApproval(ProcessEngineeringLeaderApprovalCommand approvalCommand) {
        // 总院分管领导
        List<Person> persons = personnelRemoteApiService.getPersonList(PersonQuery.builder().roleName("总院分管领导-视频监控审批").build());
        if (CollectionUtils.isEmpty(persons)) {
            throw LogicException.raise(CustomError.GENERAL_MIDDLE_LEADER_ID_MISS);
        }
        ProjectApply projectApply = projectApplyQueryService.getProjectApplyOne(ProjectApplyOneQuery.builder().id(approvalCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, approvalCommand.getMethod());

        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(projectApply.getApplyCode())
                .businessType(PROJECT_APPLY)
                .processDefinitionKey(PROCESS_PROJECT_APPLY)
                .comment(approvalCommand.getComment())
                .variables(variables)
                .build());

        projectApply.setTaskStatus(processTask.getStatus());
        projectApply.setTaskKey(processTask.getTaskDefinitionKey());
        if (approvalCommand.getMethod().equals(NOT_PASS)) {
            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
        } else {
            projectApply.setApplyStatus(ApplyStatusEnum.APPROVAL.getValue());
        }
//        if (processTask.getStatus().equals(BACK_STATE)) {
//            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
//        }

        ProjectApply saveProjectApply = projectApplyDomainService.editProjectApply(projectApply);
        // 更新处理待办
        this.updateTask(saveProjectApply);

        // 发送待办
        if (!processTask.getStatus().equals(BACK_STATE)) {
            this.sendTask(saveProjectApply, persons);
            //发送短信
            sendMessageProjectApply(persons, saveProjectApply);
        } else {
            this.returnTask(saveProjectApply);
            //发退回短信
            sendMessageProjectApplyReturnOrPass(projectApply.getApplyPerson(), projectApply, "项目免装/暂停申请审批退回");
        }
        return saveProjectApply;
    }

    @Override
    @Transactional
    public ProjectApply generalInstituteLeaderApproval(ProcessGeneralInstituteLeaderApprovalCommand approvalCommand) {
        ProjectApply projectApply = projectApplyQueryService.getProjectApplyOne(ProjectApplyOneQuery.builder().id(approvalCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, approvalCommand.getMethod());

        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(projectApply.getApplyCode())
                .businessType(PROJECT_APPLY)
                .processDefinitionKey(PROCESS_PROJECT_APPLY)
                .comment(approvalCommand.getComment())
                .variables(variables)
                .build());
        //审核通过
        if (approvalCommand.getMethod().equals(PASS)) {
            projectApply.setTaskStatus(FINISHED);
            projectApply.setApplyStatus(ApplyStatusEnum.COMPLETED.getValue());
            //更新项目的监控类型
            ProjectBasic projectBasic = projectBasicRepository.selectByProjectId(projectApply.getProject().getProjectId());
            projectBasic.setMonitorType(projectApply.getApplyType());
            projectBasicRepository.doUpdate(projectBasic);
            //发通过短信
            sendMessageProjectApplyReturnOrPass(projectApply.getApplyPerson(), projectApply, "项目免装/暂停申请审批通过");
        }

        if (approvalCommand.getMethod().equals(NOT_PASS)) {
            if (processTask != null) {
                projectApply.setTaskStatus(processTask.getStatus());
                projectApply.setTaskKey(processTask.getTaskDefinitionKey());
            }
            projectApply.setApplyStatus(ApplyStatusEnum.RETURNED.getValue());
        }

        ProjectApply saveProjectApply = projectApplyDomainService.editProjectApply(projectApply);

        this.updateTask(saveProjectApply);

        if (approvalCommand.getMethod().equals(NOT_PASS)) {
            if (null != processTask) {
                this.returnTask(saveProjectApply);
                //发退回短信
                sendMessageProjectApplyReturnOrPass(projectApply.getApplyPerson(), projectApply, "项目免装/暂停申请审批退回");
            }
        }


        return saveProjectApply;
    }

    @Override
    @Transactional
    public ProjectApply projectApplyDetail(Long id) {
        ProjectApply projectApply = projectApplyRepository.getProjectApplyOne(ProjectApplyQuery.builder().id(id).build());

        HrOrganizationResponse hrOrganizationResponse = organizationRemoteApiService.getHrOrganizationView(projectApply.getProject().getHrOrganizationId());
        ProjectBasic projectBasic = projectApply.getProject();
        projectBasic.setHrOrganizationFullName(hrOrganizationResponse.getFullName());
        projectBasic.setHrOrganizationShortName(hrOrganizationResponse.getShortName());
        projectApply.setProject(projectBasic);

        List<ProcessTask> processTasks = processRemoteService.getProcessTaskList(ProcessTaskListCommand.builder()
                .businessCode(projectApply.getApplyCode())
                .businessType(projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue()) ? PROJECT_APPLY : PROJECT_APPLY_STOP)
                .processDefinitionKey(projectApply.getApplyType().equals(MonitorTypeEnum.NOT_INSTALLED.getValue()) ? PROCESS_PROJECT_APPLY : PROCESS_PROJECT_APPLY_STOP)
                .build());
        projectApply.setProcessTask(processTasks);

        return projectApply;
    }

    @Override
    public Boolean updateMonitorType() {
        List<ProjectBasic> projectBasics = projectBasicRepository.selectProjectList();

        return true;
    }

    @Override
    @Transactional
    public ProjectApply view(Long projectId) {
        ProjectApply projectApply = new ProjectApply();
        ProjectBasic projectBasic = projectBasicRepository.selectByProjectId(projectId);

        List<ProjectApply> projectApplyList = projectApplyRepository.getProjectApplyList(ProjectApplyQuery.builder()
                .projectId(projectId)
                .applyType(projectBasic.getMonitorType())
                .applyStatus(ApplyStatusEnum.COMPLETED.getValue())
                .build());
        if (CollectionUtils.isNotEmpty(projectApplyList)) {
            projectApply = projectApplyList.get(0);
        }
        projectApply.setProject(projectBasic);

        return projectApply;
    }

    private void returnTask(ProjectApply projectApply) {
        // 发送待办
        taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                .sourceFromId(projectApply.getId())
                .taskType(MONITOR_VIEW)
                .taskName(FREE_INSTALL_APPLY_RETURN)
                .projectId(projectApply.getProject().getProjectId())
                .projectName(projectApply.getProject().getProjectName())
                .taskDescribe(projectApply.getProject().getProjectShortName())
                .startTime(projectApply.getApplyTime())
                .sponsorId(authorityUtil.getPersonId())
                .sponsorName(authorityUtil.getLoginAccess().getLastName())
                .dealPersonId(projectApply.getApplyPerson().getId())
                .dealPersonName(projectApply.getApplyPerson().getName())
                .taskStatus(DEALING)
                .build());
    }

    private void updateTask(ProjectApply projectApply) {
        // 更新待办
        List<String> oldStatus = new ArrayList<>();
        oldStatus.add(DEALING);
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(projectApply.getId())
                .taskType(MONITOR_VIEW)
                .taskName(FREE_INSTALL_APPLY)
                .projectId(projectApply.getProject().getProjectId())
                .projectName(projectApply.getProject().getProjectName())
                .taskDescribe(projectApply.getProject().getProjectShortName())
                .startTime(projectApply.getApplyTime())
                .oldStatus(oldStatus)
                .taskStatus("已完成")
                .build());
    }

    private void sendTask(ProjectApply projectApply, List<Person> persons) {
        for (Person person : persons) {
            taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                    .sourceFromId(projectApply.getId())
                    .taskType(MONITOR_VIEW)
                    .taskName(FREE_INSTALL_APPLY)
                    .projectId(projectApply.getProject().getProjectId())
                    .projectName(projectApply.getProject().getProjectName())
                    .taskDescribe(projectApply.getProject().getProjectShortName())
                    .startTime(projectApply.getApplyTime())
                    .sponsorId(authorityUtil.getPersonId())
                    .sponsorName(authorityUtil.getLoginAccess().getLastName())
                    .dealPersonId(person.getId())
                    .dealPersonName(person.getName())
                    .taskStatus(DEALING)
                    .build());
        }
    }

    private void sendMessageProjectApply(List<Person> persons, ProjectApply projectApply) {
        //发送短信
        for (Person person : persons) {
            List<String> mobile = new ArrayList<>();
            List<String> parameter = new ArrayList<>();
            mobile.add(person.getMobile());
            parameter.add(person.getName());
            parameter.add(projectApply.getProject().getProjectShortName());
            messageRemoteApiService.sendMessage(MessageSendCommand.builder()
                    .mobiles(mobile)
                    .parameters(parameter)
                    .smsTemplateName("项目免装/暂停申请审批")
                    .build());
        }
    }

    private void sendMessageProjectApplyReturnOrPass(Person person, ProjectApply projectApply, String smsTemplateName) {
        //发送短信
        List<String> mobile = new ArrayList<>();
        List<String> parameter = new ArrayList<>();
        mobile.add(person.getMobile());
        parameter.add(person.getName());
        messageRemoteApiService.sendMessage(MessageSendCommand.builder()
                .mobiles(mobile)
                .parameters(parameter)
                .smsTemplateName(smsTemplateName)
                .build());

    }

    /**
     * 保证接口幂等
     */
    private void validKey(String token) {
        if (redisUtil.incr(PROJECT_APPLY_KEY + COLONS + token, 1) != 2) {
            throw LogicException.raise(CustomError.DUPLICATE_REQUEST);
        }
    }

    @Override
    public List<HrOrganizationResponse> getOrganization(List<Long> hrOrganizationIds) {
        List<HrOrganizationResponse> hrOrganizationResponseList = organizationRemoteApiService.getHrOrganizationByHrOrganizationIds(hrOrganizationIds);
        return hrOrganizationResponseList;
    }
}
